{% extends 'common/panel.html' %}
{% block title %}{{site.name}}{% endblock title %}
{% block panel %}
    <style type="text/css" media="screen">
    svg {
        shape-rendering: auto;
    }
    
        .rule line {
          stroke: #eee;
        }

        .rule line.axis {
          stroke: #000;
        }

        .area {
          fill: lightsteelblue;
        }

        .line, circle.area {
          fill: none;
          stroke: steelblue;
          stroke-width: 0.75px;
        }

        circle.area {
          fill: #fff;
        }
        
        #protocol_listing {
            text-indent:0;
            margin:0;
            padding:15px 0;
        }
        
        .protocolElement {
            float:left;
            padding:0;
            margin:0;
            margin-right:10px;
        }
        
        .protocolElement > .toggler {
            cursor: default !important;
        }
        
        #sampling_events {
            width:95%;
            font-size:0.8em;
            padding:10px 0;
            padding-bottom:20px;
            padding-left:10px;
        }
        
        #sampling_events .year {
            float:left;
            overflow: visible;
            text-align:center;
            text-indent:-5px;
        }
        
        #sampling_events .protocol_count {
            background-color:#DEDEDE;
            float:left;
        }

        a.myPlayer, a.myPlayer:hover {
            border:solid black 4px;
            margin-top:15px;
        }
        
        a.years {
            padding:0 2px;
        }
        
        a.nowPlaying {
            background-color:#AACAF0;
        }
        
        .marinemap-panel p.project {
            margin:10px 0;
            background: url({{MEDIA_URL}}above_tabs.png) bottom no-repeat;
            padding-bottom: 20px;
        }
        
    </style>
    <script type="text/javascript" charset="utf-8">
        lingcod.onShow(function(){
            // a- tags with class "myPlayer" are transformed into video players
            flowplayer("a.myPlayer", "http://releases.flowplayer.org/swf/flowplayer-3.2.5.swf");
            
            $('a.years').click(function(e){
                $('.nowPlaying').removeClass('nowPlaying');
                $('a.myPlayer').hide();
                $($(this).attr('data-video')).show();
                $(this).addClass('nowPlaying');
                e.preventDefault();
                return false;
            });
            
            $('.years:first').click();
                        
            var years_sampled = {{site.sampling_events_json|safe}};
            var all_protocols = {{site.project.protocols_json|safe}};
            var sampled_protocols = _.unique(_.flatten(_.values(years_sampled)));
            
            // d3.select('#protocol_listing').selectAll('li')
            //     .data(all_protocols).enter()
            //     .append('li')
            //         .text(String)
            //         .attr('class', function(d){
            //             return _.include(sampled_protocols, d) ? 'visible protocolElement' : 'protocolElement';
            //         })
            //         .append('div')
            //             .attr('class', 'toggler')
            
            var sampling_years = _.keys(years_sampled);
            var min_year = {{min_year}};
            var max_year = {{max_year}};
            var year_ticks = d3.range(min_year, max_year + 1);
            var events_table = d3.select('#sampling_events');
            var color_scale = d3.scale.category20c();
            
            window.color_scale = color_scale;
            var divs = events_table.selectAll('div.protocol_count')
                .data(year_ticks).enter().append('div')
                    .html('&nbsp;')
                    .attr('class', 'protocol_count')
                    .style('width', (100.0 / year_ticks.length) + '%')
                    .style('background-color', function(d){return (d in years_sampled) ? color_scale(years_sampled[d].length) : '#EBEBEB'})
            
            window.divs = divs;
            
            events_table.append('br')
                .style('clear', 'both');
            
            events_table.selectAll('div.year')
                .data(year_ticks).enter().append('div')
                    .html(function(d, i){ if(i % 4 === 0){return d;}else{return '&nbsp;';}})
                    .attr('class', 'year')
                    .style('width', (100.0 / year_ticks.length) + '%')


            {% if temperatures %}
            // ====== Begin Temperature visualization code =======

            d3.select('#temp')
                .append('h3')
                    .text('Temperature (degrees celsius)')

            // Test run at page load. See common/map_ext.html
            if(!window.supportsSvg){
                d3.select('#temp')
                    .append('p')
                        .attr('class', 'unsupported')
                        .html('This interactive chart requires a modern browser that supports SVG. To see it, please visit this site using <a href="http://www.google.com/chrome" title="Google Chrome - Get a fast new browser. For PC, Mac, and Linux">Google Chrome</a>, <a href="http://www.mozilla.com/en-US/firefox/new/" title="Mozilla Firefox Web Browser — Free Download">Firefox</a>, or <a href="http://www.ie9enhanced.com">Internet Explorer 9</a>.')
                return;
            }
            
            Array.prototype.binarySearch = function binarySearch(find, comparator) {
                var low = 0, high = this.length - 1,
                    i, comparison;
                while (low <= high) {
                    i = parseInt((low + high) / 2, 10);
                    comparison = comparator(this[i], find);
                    if (comparison < 0) { low = i + 1; continue; };
                    if (comparison > 0) { high = i - 1; continue; };
                    return i;
                }
                return i;
            };
            
            var data = [{{temperatures|safe}}];
            
            var monthly_average = [];
            for(var i = 0; i<data.length; i++){
                var date = data[i].date;
                var first = new Date(
                    date.getFullYear(), date.getMonth(), 1, 1, 1, 1);
                if(!monthly_average[first]){
                    monthly_average[first] = {
                        n: 0,
                        sum: 0,
                        average: null
                    };
                }
                monthly_average[first].n += 1;
                monthly_average[first].sum += data[i].celsius;
            }

            
            var monthly = [];
            for(var date in monthly_average){
                var r = monthly_average[date];
                r.average = r.sum / r.n;
                r.celsius = r.average;
                r.date = new Date(date);
                if(r.date > data[0].date){
                    monthly.push(r);                    
                }
            }
            
            var w = 470,                        // width
                h = 220,                         // height
                pt = 5,                         // padding top
                pb = 5                          // bottom
                pl = 20,                        // left
                pr = 5,                         // right
                yaxisw = 13,                    // y axis labels width
                xaxish = 35,                    // x axis labels height
                legendh = 25,                   // legend height
                dw = w - (pr + pl + yaxisw),    // data range width in pixels
                dh = h - (pt + pb + xaxish + legendh),  // data height in px
                daily_color = "#B7C5CD",
                monthly_color = "#2A4AAF",
                min = d3.min(data, function(d){return d.celsius}),
                max = d3.max(data, function(d){return d.celsius}),
                earliest = d3.min(data, function(d){return d.date}),
                latest = d3.max(data, function(d){return d.date}),
                x = d3.scale.linear().domain(
                    [earliest, latest]).range([0, dw]),
                y = d3.scale.linear().domain([min, max]).range([dh, 0]);

            var years = [];
			if(earliest.getDay() == 1 && earliest.getMonth() == 1){
				years.push([new Date(earliest.getFullYear(), 0, 1, 1, 1, 1)]);				
			}
            var c = earliest;
            while(c.getFullYear() < latest.getFullYear()){
                c = new Date(c.getFullYear() + 1, 0, 1, 1, 1, 1);
                years.push(new Date(c.getTime()));
            }
            var vis = d3.select('#temp')
                .append('svg:svg')
                    .attr('id', 'panel')
                    .attr('width', w)
                    .attr('height', h)
                    .on("mousemove", update)
                    .on('mouseout', function(){update(true)})
            
            var daily_label = vis.append("svg:text")
                .attr('class', 'daily_legend')
                .attr("y", pt + 10)
                .attr("x", (w) - (110 + pr))
                .attr("fill", 'grey')
                .attr("text-anchor", "end")
                .text('● daily avg')
                .attr('style', 'font-size: 0.8em;')

            var monthly_label = vis.append("svg:text")
                .attr('class', 'monthly_legend')
                .attr("y", pt + 10)
                .attr("x", w - pr)
                .attr("fill", monthly_color)
                .attr("text-anchor", "end")
                .text('● monthly avg')
                .attr('style', 'font-size: 0.8em;')
                .attr('opacity', '0.8')
    
            var g = vis.append('svg:g')
                .attr('transform', "translate("+(pl + yaxisw)+","+(pt + legendh)+")")
            
            g.selectAll("svg:path")
                .data([data]).enter()
                .append('svg:path')
              .attr("d", d3.svg.line()
                .x(function(d) { return x(d.date); })
                .y(function(d) { return y(d.celsius)}))
              .attr('style', 'stroke: '+daily_color+';')
              .attr('class','line')
              
             g.selectAll("svg:path")
                  .data([monthly]).enter()
                  .append('svg:path')
                .attr("d", d3.svg.line()
                  .x(function(d) { return x(d.date); })
                  .y(function(d) { return y(d.celsius)})
                  .interpolate('cardinal')
                  .tension(0.65))
                .attr('style', 'stroke: '+monthly_color+';')
                .attr('class','line')
                        
            // Determines how many year labels can fit on the x-axis
			var max_year_labels = dw / (21 + 25);

			var year_labels = g.selectAll('text.year_label')
                .data(years).enter()
                .append('svg:text')
                .text(function(d){return d.getFullYear()})
                .attr('x', function(d){return x(d)})
                .attr('y', dh + 20)
				.attr('opacity', function(d, i){ return i % Math.round(years.length / max_year_labels) ? '0' : '1'})
                .attr('style', 'font-size: 0.7em;text-anchor:middle;')

            var year_tics = g.selectAll('line.year')
                .data(years).enter()
                .append('svg:line')
                .attr('class', 'year')
                .attr('x1', function(d){return x(d)})
                .attr('y1', dh + 10)
                .attr('x2', function(d){return x(d)})
                .attr('y2', dh + 5)
				.attr('style', 'stroke:black;stroke-width:1;')

            var month_tics = g.selectAll('line.month')
                .data(monthly).enter()
                .append('svg:line')
                .attr('class', 'month')
                .attr('x1', function(d){return x(d.date)})
                .attr('y1', dh + 8)
                .attr('x2', function(d){return x(d.date)})
                .attr('y2', dh + 7)
				.attr('style', 'stroke:black;stroke-width:0.5;')
			
			
			var yaxis_labels = g.selectAll('text.celsius')
			    .data(y.ticks(4)).enter()
			        .append('svg:text')
			        .text(function(d){return Math.round(d * 100) / 100 + '°'})
			        .attr('x', 0 - yaxisw - 16)
			        .attr('y', function(d){return y(d) + 2})
			        .attr('style', 'font-size: 0.7em;')

			var yaxis_ticks = g.selectAll('line.celsius')
			    .data(y.ticks(4)).enter()
			        .append('svg:line')
			        .attr('class', 'celsius')
                    .attr('x1', 0 - yaxisw + 5)
                    .attr('y1', function(d){return y(d)})
                    .attr('x2', 0 - yaxisw)
                    .attr('y2', function(d){return y(d)})
    				.attr('style', 'stroke:black;stroke-width:1px;')

			var yaxis_minor_ticks = g.selectAll('line.minor_celsius')
			    .data(y.ticks(10)).enter()
			        .append('svg:line')
			        .attr('class', 'minor_celsius')
                    .attr('x1', 0 - yaxisw + 5)
                    .attr('y1', function(d){return y(d)})
                    .attr('x2', 0 - yaxisw + 3)
                    .attr('y2', function(d){return y(d)})
    				.attr('style', 'stroke:black;stroke-width:1px;')
            
            var selectedData = [];
            var selectedDaily = [];
            var selectedMonthly = [];
            var interp = d3.interpolate(0, dw);
            var timeout;
            var date = null;            
            function update(a) {
                if(timeout){
                    clearTimeout(timeout);
                }
                var mousex = d3.svg.mouse(vis.select('g')[0][0])[0];
                if(mousex < 0){
                    a = true;
                }
                date = new Date(x.invert(mousex));
                timeout = setTimeout(function(){
                    date.setHours(0);
                    date.setMinutes(0);
                    date.setSeconds(0);
                    date.setMilliseconds(0);
                    var selected_date = date;
                    var original = latest;
                    if(selectedData[0]){
                        original = new Date(selectedData[0].getTime());
                    }
                    selectedData.pop();
                    timeout = null;
                    if(!a){
                        selectedData.push(selected_date);
                    }
                    var selected = g.selectAll("line.selected")
                        .data(selectedData, function(d){return d.getTime()});
                    selected.enter()
                        .insert('svg:line', 'path')
                            .attr('class', 'selected')
                            .attr('stroke', 'grey')
                            .attr('stroke-width', '0.5px')
                            .attr('style', 'stroke-dasharray: 3, 3;')
                            .attr('x1', function(d){return x(original)})
                            .attr('x2', function(d){return x(original)})
                            .attr("y1", 0)
                            .attr("y2", dh + 10)
                            .transition().duration(300)
                                .attr('x1', function(d, i, b){return x(d)})
                                .attr('x2', function(d, i, b){return x(d)})
                    
                    selected.exit().remove();

                    var index = data.binarySearch(selected_date, function(a, b){
                        return a.date.getTime() - b.getTime()
                    });
                    
                    var selected_record = data[index];
                    selectedDaily.pop();             
                    if(selected_record){
                        if(!a){
                            selectedDaily.push(selected_record);
                        }
                    }
                    var dailypin = g.selectAll('circle.dailypin')
                        .data(selectedDaily, function(d){return d.date.getTime()})
                    dailypin.enter()
                        .append('svg:circle')
                            .attr('class', 'dailypin')
                            .attr('stroke', 'black')
                            .attr('stroke-width', 0.5)
                            .attr('cx', function(d){return x(d.date);})
                            .attr('cy', function(d){return y(d.celsius);})
                            .attr('r', 2)
                            .attr('fill', '#CCC')
                    dailypin.exit().remove();
                    var daylabel = vis.selectAll('text.daylabel')
                        .data(selectedDaily, function(d){return d.date.getTime()});
                    daylabel.enter()
                        .append('svg:text')
                            .attr('class', 'daylabel')
                            .text(function(d){return d.date.toDateString()})
                            .attr('x', w - pr)
                            .attr('y', h - 5)
                            .attr("text-anchor", "end")
                            .attr('style', 'font-size: 0.7em; fill:grey;')
                            
                        
                    daylabel.exit().remove()
                    
                    var selected_month = new Date(date.getFullYear(), date.getMonth(), 1, 1, 1, 1);
                    if(selected_date.getDate() > 15){
                        selected_month.setMonth(selected_month.getMonth() + 1);
                    }
                    
                    var index = monthly.binarySearch(selected_month, function(a, b){
                        return a.date.getTime() - b.getTime()
                    });
                    
                    var selected_month_record = monthly[index];
                    // var selected_month_record = false;
                    // for(var i = 0; i<monthly.length;i++){
                    //     if(monthly[i].date.getTime() == selected_month.getTime()){
                    //         selected_month_record = monthly[i];
                    //         break;             
                    //     }
                    // }
                    selectedMonthly.pop();             
                    if(selected_month_record){
                        if(!a){
                            selectedMonthly.push(selected_month_record);
                        }
                    }
                    var monthlypin = g.selectAll('circle.monthly')
                        .data(selectedMonthly, function(d){return d.date.getTime()})
                    
                    monthlypin.enter()
                        .append('svg:circle')
                            .attr('class', 'monthly')
                            .attr('stroke', 'black')
                            .attr('stroke-width', 0.5)
                            .attr('cx', function(d){return x(d.date);})
                            .attr('cy', function(d){return y(d.celsius);})
                            .attr('r', 2)
                            .attr('fill', '#004080')
                    
                    monthlypin.exit().remove();
                    
                    if(!a){
                        vis.select('text.monthly_legend')
                            .text(selected_month_record ? Math.round(selected_month_record.celsius * 100) / 100 + ' monthly avg' : '● monthly avg')
                        vis.select('text.daily_legend')
                            .text(selected_record ? Math.round(selected_record.celsius * 100) / 100 + ' daily avg' : '● daily avg')
                    }else{
                        vis.select('text.monthly_legend')
                            .text('● monthly avg')                        
                        vis.select('text.daily_legend')
                            .text('● daily avg')                        
                    }
                }, 5);
            }
            {% endif %}
        });
    </script>
    <h1>{{site.name}}</h1>
    <p class="project"><img style="margin-bottom:-5px;" class="logo" src="{{MEDIA_URL}}kfm/logo_small.png"/>A National Park Service Kelp Forest Monitoring Site</p>
    <div class="tabs">
        <ul>
            <li><a href="#SiteInfo"><span>Site Info</span></a></li>
            <li><a href="{% url monitoring.views.species_lists site.pk %}"><span>Species Lists</span></a></li>
            <li><a href="{% url monitoring.views.chart site.pk %}"><span>Create a Chart</span></a></li>
        </ul>
        <div id="SiteInfo">
            <h3>Sampled {{site.earliest}} - {{site.latest}}</h3>
            {# <ul id="protocol_listing"></ul> #}
            {# <br style="clear:both;"> #}
            <div id="sampling_events"></div>
            <div class="videos">
                <h3>Underwater Video Transects</h3>
                {% for video in site.videos.all %}
                    <a class="myPlayer" id="video_{{video.pk}}"
                    	href="{{video.url}}" {% if video.full_thumbnail %}style="background-image:url('{{video.full_thumbnail}}');"{% endif %}>
                        <img src="{{MEDIA_URL}}/images/play_video.png" alt="{{video.site.name}} - {{video.year}}"/>
                    </a>
                {% endfor %}
                {% for video in site.videos.all %}
                    <a class="years" data-video="#video_{{video.pk}}" href="#video_{{video.pk}}">{{video.year}}</a>
                {% endfor %}
            </div>
            <div id="temp"></div>
        </div>
    </div>
{% endblock panel %}